{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fe917f8d-541e-4df9-a5ac-d1fbd5a9d272",
   "metadata": {},
   "source": [
    "# 决策树和随机森林"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f748c5dd-3a28-44a3-bb55-46736e78fa5f",
   "metadata": {},
   "source": [
    "## 决策树"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "cb732478-d0d2-4441-9759-a311e0c4a6d4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "\n",
    "from sklearn import tree\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import classification_report\n",
    "from sklearn.metrics import confusion_matrix\n",
    "from sklearn.metrics import roc_curve\n",
    "from sklearn.metrics import auc\n",
    "\n",
    "from IPython.core.interactiveshell import InteractiveShell\n",
    "InteractiveShell.ast_node_interactivity = \"all\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "0437388f-b6e6-43c0-9d98-b4b5e2ad20da",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>checking</th>\n",
       "      <th>duration</th>\n",
       "      <th>history</th>\n",
       "      <th>purpose</th>\n",
       "      <th>amount</th>\n",
       "      <th>savings</th>\n",
       "      <th>employed</th>\n",
       "      <th>installp</th>\n",
       "      <th>marital</th>\n",
       "      <th>coapp</th>\n",
       "      <th>...</th>\n",
       "      <th>property</th>\n",
       "      <th>age</th>\n",
       "      <th>other</th>\n",
       "      <th>housing</th>\n",
       "      <th>existcr</th>\n",
       "      <th>job</th>\n",
       "      <th>depends</th>\n",
       "      <th>telephon</th>\n",
       "      <th>foreign</th>\n",
       "      <th>good_bad</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>6</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>1169</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>...</td>\n",
       "      <td>1</td>\n",
       "      <td>67</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>good</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>48</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>5951</td>\n",
       "      <td>1</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>...</td>\n",
       "      <td>1</td>\n",
       "      <td>22</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>bad</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4</td>\n",
       "      <td>12</td>\n",
       "      <td>4</td>\n",
       "      <td>6</td>\n",
       "      <td>2096</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>...</td>\n",
       "      <td>1</td>\n",
       "      <td>49</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>good</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1</td>\n",
       "      <td>42</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>7882</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>3</td>\n",
       "      <td>...</td>\n",
       "      <td>2</td>\n",
       "      <td>45</td>\n",
       "      <td>3</td>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>good</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1</td>\n",
       "      <td>24</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>4870</td>\n",
       "      <td>1</td>\n",
       "      <td>3</td>\n",
       "      <td>3</td>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>...</td>\n",
       "      <td>4</td>\n",
       "      <td>53</td>\n",
       "      <td>3</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>bad</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>5 rows × 21 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "   checking  duration  history purpose  amount  savings  employed  installp  \\\n",
       "0         1         6        4       3    1169        5         5         4   \n",
       "1         2        48        2       3    5951        1         3         2   \n",
       "2         4        12        4       6    2096        1         4         2   \n",
       "3         1        42        2       2    7882        1         4         2   \n",
       "4         1        24        3       0    4870        1         3         3   \n",
       "\n",
       "   marital  coapp  ...  property  age  other  housing  existcr  job  depends  \\\n",
       "0        3      1  ...         1   67      3        2        2    3        1   \n",
       "1        2      1  ...         1   22      3        2        1    3        1   \n",
       "2        3      1  ...         1   49      3        2        1    2        2   \n",
       "3        3      3  ...         2   45      3        3        1    3        2   \n",
       "4        3      1  ...         4   53      3        3        2    3        2   \n",
       "\n",
       "   telephon  foreign  good_bad  \n",
       "0         2        1      good  \n",
       "1         1        1       bad  \n",
       "2         1        1      good  \n",
       "3         1        1      good  \n",
       "4         1        1       bad  \n",
       "\n",
       "[5 rows x 21 columns]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 利用pandas导入csv数据，查看前5行导入结果看是否正常\n",
    "import pandas as pd\n",
    "credit_df = pd.read_csv(\"credit.csv\")\n",
    "credit_df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ad74525-2858-4e28-867b-0e50f8d8d190",
   "metadata": {},
   "source": [
    "### 检查数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "cbc9c452-96a3-4805-8306-8dc27880d1c4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 1000 entries, 0 to 999\n",
      "Data columns (total 21 columns):\n",
      " #   Column    Non-Null Count  Dtype \n",
      "---  ------    --------------  ----- \n",
      " 0   checking  1000 non-null   int64 \n",
      " 1   duration  1000 non-null   int64 \n",
      " 2   history   1000 non-null   int64 \n",
      " 3   purpose   1000 non-null   object\n",
      " 4   amount    1000 non-null   int64 \n",
      " 5   savings   1000 non-null   int64 \n",
      " 6   employed  1000 non-null   int64 \n",
      " 7   installp  1000 non-null   int64 \n",
      " 8   marital   1000 non-null   int64 \n",
      " 9   coapp     1000 non-null   int64 \n",
      " 10  resident  1000 non-null   int64 \n",
      " 11  property  1000 non-null   int64 \n",
      " 12  age       1000 non-null   int64 \n",
      " 13  other     1000 non-null   int64 \n",
      " 14  housing   1000 non-null   int64 \n",
      " 15  existcr   1000 non-null   int64 \n",
      " 16  job       1000 non-null   int64 \n",
      " 17  depends   1000 non-null   int64 \n",
      " 18  telephon  1000 non-null   int64 \n",
      " 19  foreign   1000 non-null   int64 \n",
      " 20  good_bad  1000 non-null   object\n",
      "dtypes: int64(19), object(2)\n",
      "memory usage: 164.2+ KB\n"
     ]
    }
   ],
   "source": [
    "credit_df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4f2433cb-1c51-45a6-bda9-793c60fb74e4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "checking    0\n",
       "duration    0\n",
       "history     0\n",
       "purpose     0\n",
       "amount      0\n",
       "savings     0\n",
       "employed    0\n",
       "installp    0\n",
       "marital     0\n",
       "coapp       0\n",
       "resident    0\n",
       "property    0\n",
       "age         0\n",
       "other       0\n",
       "housing     0\n",
       "existcr     0\n",
       "job         0\n",
       "depends     0\n",
       "telephon    0\n",
       "foreign     0\n",
       "good_bad    0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "credit_df.isnull().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "119e2532-1fe1-428e-a4cb-353b24271c17",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>checking</th>\n",
       "      <th>duration</th>\n",
       "      <th>history</th>\n",
       "      <th>amount</th>\n",
       "      <th>savings</th>\n",
       "      <th>employed</th>\n",
       "      <th>installp</th>\n",
       "      <th>marital</th>\n",
       "      <th>coapp</th>\n",
       "      <th>resident</th>\n",
       "      <th>property</th>\n",
       "      <th>age</th>\n",
       "      <th>other</th>\n",
       "      <th>housing</th>\n",
       "      <th>existcr</th>\n",
       "      <th>job</th>\n",
       "      <th>depends</th>\n",
       "      <th>telephon</th>\n",
       "      <th>foreign</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.00000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.00000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.000000</td>\n",
       "      <td>1000.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>2.577000</td>\n",
       "      <td>20.903000</td>\n",
       "      <td>2.54500</td>\n",
       "      <td>3271.258000</td>\n",
       "      <td>2.105000</td>\n",
       "      <td>3.384000</td>\n",
       "      <td>2.973000</td>\n",
       "      <td>2.68200</td>\n",
       "      <td>1.145000</td>\n",
       "      <td>2.845000</td>\n",
       "      <td>2.358000</td>\n",
       "      <td>35.546000</td>\n",
       "      <td>2.675000</td>\n",
       "      <td>1.929000</td>\n",
       "      <td>1.407000</td>\n",
       "      <td>2.904000</td>\n",
       "      <td>1.155000</td>\n",
       "      <td>1.404000</td>\n",
       "      <td>1.037000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>1.257638</td>\n",
       "      <td>12.058814</td>\n",
       "      <td>1.08312</td>\n",
       "      <td>2822.736876</td>\n",
       "      <td>1.580023</td>\n",
       "      <td>1.208306</td>\n",
       "      <td>1.118715</td>\n",
       "      <td>0.70808</td>\n",
       "      <td>0.477706</td>\n",
       "      <td>1.103718</td>\n",
       "      <td>1.050209</td>\n",
       "      <td>11.375469</td>\n",
       "      <td>0.705601</td>\n",
       "      <td>0.531264</td>\n",
       "      <td>0.577654</td>\n",
       "      <td>0.653614</td>\n",
       "      <td>0.362086</td>\n",
       "      <td>0.490943</td>\n",
       "      <td>0.188856</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>0.00000</td>\n",
       "      <td>250.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.00000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>19.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>1.000000</td>\n",
       "      <td>12.000000</td>\n",
       "      <td>2.00000</td>\n",
       "      <td>1365.500000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.00000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>27.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>2.000000</td>\n",
       "      <td>18.000000</td>\n",
       "      <td>2.00000</td>\n",
       "      <td>2319.500000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.00000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>33.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>4.000000</td>\n",
       "      <td>24.000000</td>\n",
       "      <td>4.00000</td>\n",
       "      <td>3972.250000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>3.00000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>42.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>1.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>4.000000</td>\n",
       "      <td>72.000000</td>\n",
       "      <td>4.00000</td>\n",
       "      <td>18424.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.00000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>75.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>2.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          checking     duration     history        amount      savings  \\\n",
       "count  1000.000000  1000.000000  1000.00000   1000.000000  1000.000000   \n",
       "mean      2.577000    20.903000     2.54500   3271.258000     2.105000   \n",
       "std       1.257638    12.058814     1.08312   2822.736876     1.580023   \n",
       "min       1.000000     4.000000     0.00000    250.000000     1.000000   \n",
       "25%       1.000000    12.000000     2.00000   1365.500000     1.000000   \n",
       "50%       2.000000    18.000000     2.00000   2319.500000     1.000000   \n",
       "75%       4.000000    24.000000     4.00000   3972.250000     3.000000   \n",
       "max       4.000000    72.000000     4.00000  18424.000000     5.000000   \n",
       "\n",
       "          employed     installp     marital        coapp     resident  \\\n",
       "count  1000.000000  1000.000000  1000.00000  1000.000000  1000.000000   \n",
       "mean      3.384000     2.973000     2.68200     1.145000     2.845000   \n",
       "std       1.208306     1.118715     0.70808     0.477706     1.103718   \n",
       "min       1.000000     1.000000     1.00000     1.000000     1.000000   \n",
       "25%       3.000000     2.000000     2.00000     1.000000     2.000000   \n",
       "50%       3.000000     3.000000     3.00000     1.000000     3.000000   \n",
       "75%       5.000000     4.000000     3.00000     1.000000     4.000000   \n",
       "max       5.000000     4.000000     4.00000     3.000000     4.000000   \n",
       "\n",
       "          property          age        other      housing      existcr  \\\n",
       "count  1000.000000  1000.000000  1000.000000  1000.000000  1000.000000   \n",
       "mean      2.358000    35.546000     2.675000     1.929000     1.407000   \n",
       "std       1.050209    11.375469     0.705601     0.531264     0.577654   \n",
       "min       1.000000    19.000000     1.000000     1.000000     1.000000   \n",
       "25%       1.000000    27.000000     3.000000     2.000000     1.000000   \n",
       "50%       2.000000    33.000000     3.000000     2.000000     1.000000   \n",
       "75%       3.000000    42.000000     3.000000     2.000000     2.000000   \n",
       "max       4.000000    75.000000     3.000000     3.000000     4.000000   \n",
       "\n",
       "               job      depends     telephon      foreign  \n",
       "count  1000.000000  1000.000000  1000.000000  1000.000000  \n",
       "mean      2.904000     1.155000     1.404000     1.037000  \n",
       "std       0.653614     0.362086     0.490943     0.188856  \n",
       "min       1.000000     1.000000     1.000000     1.000000  \n",
       "25%       3.000000     1.000000     1.000000     1.000000  \n",
       "50%       3.000000     1.000000     1.000000     1.000000  \n",
       "75%       3.000000     1.000000     2.000000     1.000000  \n",
       "max       4.000000     2.000000     2.000000     2.000000  "
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "credit_df.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c9896f1a-8d58-4470-864e-ccc7e172c175",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>checking</th>\n",
       "      <th>duration</th>\n",
       "      <th>history</th>\n",
       "      <th>purpose</th>\n",
       "      <th>amount</th>\n",
       "      <th>savings</th>\n",
       "      <th>employed</th>\n",
       "      <th>installp</th>\n",
       "      <th>marital</th>\n",
       "      <th>coapp</th>\n",
       "      <th>...</th>\n",
       "      <th>property</th>\n",
       "      <th>age</th>\n",
       "      <th>other</th>\n",
       "      <th>housing</th>\n",
       "      <th>existcr</th>\n",
       "      <th>job</th>\n",
       "      <th>depends</th>\n",
       "      <th>telephon</th>\n",
       "      <th>foreign</th>\n",
       "      <th>good_bad</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>0 rows × 21 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "Empty DataFrame\n",
       "Columns: [checking, duration, history, purpose, amount, savings, employed, installp, marital, coapp, resident, property, age, other, housing, existcr, job, depends, telephon, foreign, good_bad]\n",
       "Index: []\n",
       "\n",
       "[0 rows x 21 columns]"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "credit_df[credit_df.duplicated()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "597ade68-1e09-495d-a0f3-38649904c0cc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3    280\n",
      "0    234\n",
      "2    181\n",
      "1    103\n",
      "9     97\n",
      "6     50\n",
      "5     22\n",
      "4     12\n",
      "X     12\n",
      "8      9\n",
      "Name: purpose, dtype: int64\n",
      "good    700\n",
      "bad     300\n",
      "Name: good_bad, dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# 通过value_counts()函数对类别型变量进行频数统计\n",
    "print(credit_df.purpose.value_counts())\n",
    "print(credit_df.good_bad.value_counts())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62ace678-1c13-4c94-830c-f08017b35a7c",
   "metadata": {},
   "source": [
    "### 数据处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "f388929a-f83b-49b8-b24c-d7b77aa1ea65",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>purpose_0</th>\n",
       "      <th>purpose_1</th>\n",
       "      <th>purpose_2</th>\n",
       "      <th>purpose_3</th>\n",
       "      <th>purpose_4</th>\n",
       "      <th>purpose_5</th>\n",
       "      <th>purpose_6</th>\n",
       "      <th>purpose_8</th>\n",
       "      <th>purpose_9</th>\n",
       "      <th>purpose_X</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   purpose_0  purpose_1  purpose_2  purpose_3  purpose_4  purpose_5  \\\n",
       "0          0          0          0          1          0          0   \n",
       "1          0          0          0          1          0          0   \n",
       "2          0          0          0          0          0          0   \n",
       "3          0          0          1          0          0          0   \n",
       "4          1          0          0          0          0          0   \n",
       "\n",
       "   purpose_6  purpose_8  purpose_9  purpose_X  \n",
       "0          0          0          0          0  \n",
       "1          0          0          0          0  \n",
       "2          1          0          0          0  \n",
       "3          0          0          0          0  \n",
       "4          0          0          0          0  "
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 把类别型变量进行独热编码(1->N)\n",
    "checking = pd.get_dummies(credit_df.checking,prefix='checking')\n",
    "history = pd.get_dummies(credit_df.history,prefix='history')\n",
    "purpose = pd.get_dummies(credit_df.purpose,prefix='purpose')\n",
    "savings = pd.get_dummies(credit_df.savings,prefix='savings')\n",
    "employed = pd.get_dummies(credit_df.employed,prefix='employed')\n",
    "installp = pd.get_dummies(credit_df.installp,prefix='installp')\n",
    "marital = pd.get_dummies(credit_df.marital,prefix='marital')\n",
    "coapp = pd.get_dummies(credit_df.coapp,prefix='coapp')\n",
    "installp = pd.get_dummies(credit_df.installp,prefix='installp')\n",
    "resident = pd.get_dummies(credit_df.resident,prefix='resident')\n",
    "property = pd.get_dummies(credit_df.property,prefix='property')\n",
    "housing = pd.get_dummies(credit_df.housing,prefix='housing')\n",
    "existcr = pd.get_dummies(credit_df.existcr,prefix='existcr')\n",
    "job = pd.get_dummies(credit_df.job,prefix='job')\n",
    "depends = pd.get_dummies(credit_df.depends,prefix='depends')\n",
    "telephon = pd.get_dummies(credit_df.telephon,prefix='telephon')\n",
    "foreign = pd.get_dummies(credit_df.foreign,prefix='foreign')\n",
    "\n",
    "# 随便查看一个编码后的数据\n",
    "purpose.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "77f883c8-0ea3-48d1-8d49-efd5a916fbd3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>duration</th>\n",
       "      <th>amount</th>\n",
       "      <th>age</th>\n",
       "      <th>checking_1</th>\n",
       "      <th>checking_2</th>\n",
       "      <th>checking_3</th>\n",
       "      <th>checking_4</th>\n",
       "      <th>history_0</th>\n",
       "      <th>history_1</th>\n",
       "      <th>history_2</th>\n",
       "      <th>...</th>\n",
       "      <th>job_1</th>\n",
       "      <th>job_2</th>\n",
       "      <th>job_3</th>\n",
       "      <th>job_4</th>\n",
       "      <th>depends_1</th>\n",
       "      <th>depends_2</th>\n",
       "      <th>telephon_1</th>\n",
       "      <th>telephon_2</th>\n",
       "      <th>foreign_1</th>\n",
       "      <th>foreign_2</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>6</td>\n",
       "      <td>1169</td>\n",
       "      <td>67</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>48</td>\n",
       "      <td>5951</td>\n",
       "      <td>22</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>12</td>\n",
       "      <td>2096</td>\n",
       "      <td>49</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>42</td>\n",
       "      <td>7882</td>\n",
       "      <td>45</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>24</td>\n",
       "      <td>4870</td>\n",
       "      <td>53</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>5 rows × 72 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "   duration  amount  age  checking_1  checking_2  checking_3  checking_4  \\\n",
       "0         6    1169   67           1           0           0           0   \n",
       "1        48    5951   22           0           1           0           0   \n",
       "2        12    2096   49           0           0           0           1   \n",
       "3        42    7882   45           1           0           0           0   \n",
       "4        24    4870   53           1           0           0           0   \n",
       "\n",
       "   history_0  history_1  history_2  ...  job_1  job_2  job_3  job_4  \\\n",
       "0          0          0          0  ...      0      0      1      0   \n",
       "1          0          0          1  ...      0      0      1      0   \n",
       "2          0          0          0  ...      0      1      0      0   \n",
       "3          0          0          1  ...      0      0      1      0   \n",
       "4          0          0          0  ...      0      0      1      0   \n",
       "\n",
       "   depends_1  depends_2  telephon_1  telephon_2  foreign_1  foreign_2  \n",
       "0          1          0           0           1          1          0  \n",
       "1          1          0           1           0          1          0  \n",
       "2          0          1           1           0          1          0  \n",
       "3          0          1           1           0          1          0  \n",
       "4          0          1           1           0          1          0  \n",
       "\n",
       "[5 rows x 72 columns]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 利用concat()函数把转换后的数据对象全部合并在一起变成新的数据对象，命名为trainData_X\n",
    "trainData_X = pd.concat([credit_df.duration, credit_df.amount, credit_df.age, checking, history, purpose, savings, employed, installp, marital, coapp, installp, resident, property, housing, existcr, job, depends, telephon, foreign], axis=1)\n",
    "trainData_X.head()\n",
    "# 72 columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c06d86ad-ac24-4047-b484-4a815cc884d8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    700\n",
       "1    300\n",
       "Name: target, dtype: int64"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 构造目标变量y的数据对象\n",
    "# 当前的目标变量good_bad的取值是'good'和'bad'，一般我们习惯把二分类的类别值编码为0和1，1一般表示类别比较少的那一类，他们往往是我们感兴趣的\n",
    "credit_df['target'] = 0\n",
    "credit_df.loc[(credit_df.good_bad == 'bad'), 'target'] = 1\n",
    "\n",
    "trainData_y = credit_df['target'] \n",
    "trainData_y.value_counts()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "155ed159-9b1c-41a7-af04-3d7798761ca9",
   "metadata": {},
   "source": [
    "### 数据拆分"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "722904cf-021f-4ec6-9505-9793c7f26878",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    199\n",
       "1    101\n",
       "Name: target, dtype: int64"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "X_train,X_test,y_train,y_test = train_test_split(trainData_X,trainData_y,test_size=0.3,random_state=2048)\n",
    "\n",
    "y_test.value_counts()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33c8554a-b40c-4e67-bc7f-bab54be654e2",
   "metadata": {},
   "source": [
    "### 训练决策树模型并查看模型结果和数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "e4255388-2927-41e9-a740-0937671cbbe9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-1 {color: black;background-color: white;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>DecisionTreeClassifier(max_depth=10)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" checked><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">DecisionTreeClassifier</label><div class=\"sk-toggleable__content\"><pre>DecisionTreeClassifier(max_depth=10)</pre></div></div></div></div></div>"
      ],
      "text/plain": [
       "DecisionTreeClassifier(max_depth=10)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.tree import DecisionTreeClassifier\n",
    "\n",
    "dtree = DecisionTreeClassifier(max_depth=10)\n",
    "dtree.fit(X_train,y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "47bb5b57-5f67-459d-9ee1-ddeeb1c31ad2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.10146195, 0.16496689, 0.08289807, 0.        , 0.00633838,\n",
       "       0.        , 0.12837154, 0.02479451, 0.04281327, 0.01884668,\n",
       "       0.00436754, 0.01140908, 0.01235984, 0.01640178, 0.00660248,\n",
       "       0.        , 0.        , 0.00651948, 0.00177266, 0.        ,\n",
       "       0.03559237, 0.        , 0.04946573, 0.02740458, 0.00705467,\n",
       "       0.        , 0.        , 0.02868117, 0.        , 0.00792297,\n",
       "       0.        , 0.02052866, 0.00713068, 0.        , 0.02010172,\n",
       "       0.        , 0.        , 0.0050707 , 0.01510577, 0.        ,\n",
       "       0.01730297, 0.01044812, 0.01523301, 0.        , 0.        ,\n",
       "       0.        , 0.00930225, 0.01487256, 0.        , 0.        ,\n",
       "       0.        , 0.00855681, 0.02097184, 0.02143833, 0.        ,\n",
       "       0.        , 0.        , 0.        , 0.        , 0.00578104,\n",
       "       0.        , 0.        , 0.        , 0.        , 0.        ,\n",
       "       0.00151019, 0.        , 0.        , 0.01426135, 0.        ,\n",
       "       0.        , 0.00633838])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dtree.feature_importances_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "2a22a264-b3d4-454a-81fd-2a6d3dd67581",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>feature</th>\n",
       "      <th>importance</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>amount</td>\n",
       "      <td>0.164967</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>checking_4</td>\n",
       "      <td>0.128372</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>duration</td>\n",
       "      <td>0.101462</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>age</td>\n",
       "      <td>0.082898</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>22</th>\n",
       "      <td>savings_1</td>\n",
       "      <td>0.049466</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>history_1</td>\n",
       "      <td>0.042813</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20</th>\n",
       "      <td>purpose_9</td>\n",
       "      <td>0.035592</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>27</th>\n",
       "      <td>employed_1</td>\n",
       "      <td>0.028681</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>23</th>\n",
       "      <td>savings_2</td>\n",
       "      <td>0.027405</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>history_0</td>\n",
       "      <td>0.024795</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>53</th>\n",
       "      <td>property_3</td>\n",
       "      <td>0.021438</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>52</th>\n",
       "      <td>property_2</td>\n",
       "      <td>0.020972</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>31</th>\n",
       "      <td>employed_5</td>\n",
       "      <td>0.020529</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>34</th>\n",
       "      <td>installp_3</td>\n",
       "      <td>0.020102</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>history_2</td>\n",
       "      <td>0.018847</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>40</th>\n",
       "      <td>coapp_1</td>\n",
       "      <td>0.017303</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>purpose_1</td>\n",
       "      <td>0.016402</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>42</th>\n",
       "      <td>coapp_3</td>\n",
       "      <td>0.015233</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>38</th>\n",
       "      <td>marital_3</td>\n",
       "      <td>0.015106</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>47</th>\n",
       "      <td>resident_1</td>\n",
       "      <td>0.014873</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       feature  importance\n",
       "1       amount    0.164967\n",
       "6   checking_4    0.128372\n",
       "0     duration    0.101462\n",
       "2          age    0.082898\n",
       "22   savings_1    0.049466\n",
       "8    history_1    0.042813\n",
       "20   purpose_9    0.035592\n",
       "27  employed_1    0.028681\n",
       "23   savings_2    0.027405\n",
       "7    history_0    0.024795\n",
       "53  property_3    0.021438\n",
       "52  property_2    0.020972\n",
       "31  employed_5    0.020529\n",
       "34  installp_3    0.020102\n",
       "9    history_2    0.018847\n",
       "40     coapp_1    0.017303\n",
       "13   purpose_1    0.016402\n",
       "42     coapp_3    0.015233\n",
       "38   marital_3    0.015106\n",
       "47  resident_1    0.014873"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查看特征的重要性排序\n",
    "\n",
    "import pandas as pd\n",
    "features = pd.DataFrame()\n",
    "\n",
    "# 为空集合features创建两个列并赋值\n",
    "features['feature'] = X_train.columns\n",
    "features['importance'] = dtree.feature_importances_\n",
    "\n",
    "# 降序排列\n",
    "features = features.sort_values(by =['importance'], ascending=False)    \n",
    "\n",
    "# 显示最重要的前10个特征变量\n",
    "features.head(20)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "997c8131-082b-4a97-97c7-1dd9b09f0cb8",
   "metadata": {},
   "source": [
    "### 调参"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "8ea30d41-5d08-4bc2-bc40-e5f2716feff8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 1], dtype=int64)"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "text/plain": [
       "array([0.10146195, 0.16496689, 0.08289807, 0.        , 0.00633838,\n",
       "       0.        , 0.12837154, 0.02479451, 0.04281327, 0.01884668,\n",
       "       0.00436754, 0.01140908, 0.01235984, 0.01640178, 0.00660248,\n",
       "       0.        , 0.        , 0.00651948, 0.00177266, 0.        ,\n",
       "       0.03559237, 0.        , 0.04946573, 0.02740458, 0.00705467,\n",
       "       0.        , 0.        , 0.02868117, 0.        , 0.00792297,\n",
       "       0.        , 0.02052866, 0.00713068, 0.        , 0.02010172,\n",
       "       0.        , 0.        , 0.0050707 , 0.01510577, 0.        ,\n",
       "       0.01730297, 0.01044812, 0.01523301, 0.        , 0.        ,\n",
       "       0.        , 0.00930225, 0.01487256, 0.        , 0.        ,\n",
       "       0.        , 0.00855681, 0.02097184, 0.02143833, 0.        ,\n",
       "       0.        , 0.        , 0.        , 0.        , 0.00578104,\n",
       "       0.        , 0.        , 0.        , 0.        , 0.        ,\n",
       "       0.00151019, 0.        , 0.        , 0.01426135, 0.        ,\n",
       "       0.        , 0.00633838])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "text/plain": [
       "72"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "ename": "AttributeError",
     "evalue": "'DecisionTreeClassifier' object has no attribute 'n_features_'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[15], line 6\u001b[0m\n\u001b[0;32m      4\u001b[0m dtree\u001b[38;5;241m.\u001b[39mmax_features_\n\u001b[0;32m      5\u001b[0m dtree\u001b[38;5;241m.\u001b[39mn_classes_\n\u001b[1;32m----> 6\u001b[0m \u001b[43mdtree\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mn_features_\u001b[49m\n\u001b[0;32m      7\u001b[0m dtree\u001b[38;5;241m.\u001b[39mn_outputs_\n\u001b[0;32m      8\u001b[0m dtree\u001b[38;5;241m.\u001b[39mtree_\n",
      "\u001b[1;31mAttributeError\u001b[0m: 'DecisionTreeClassifier' object has no attribute 'n_features_'"
     ]
    }
   ],
   "source": [
    "# 查看模型结果\n",
    "dtree.classes_\n",
    "dtree.feature_importances_\n",
    "dtree.max_features_\n",
    "dtree.n_classes_\n",
    "dtree.n_features_\n",
    "dtree.n_outputs_\n",
    "dtree.tree_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "72a1b7a4-d9bc-4a08-9e8a-fbe628f44e7b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-2 {color: black;background-color: white;}#sk-container-id-2 pre{padding: 0;}#sk-container-id-2 div.sk-toggleable {background-color: white;}#sk-container-id-2 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-2 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-2 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-2 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-2 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-2 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-2 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-2 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-2 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-2 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-2 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-2 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-2 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-2 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-2 div.sk-item {position: relative;z-index: 1;}#sk-container-id-2 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-2 div.sk-item::before, #sk-container-id-2 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-2 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-2 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-2 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-2 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-2 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-2 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-2 div.sk-label-container {text-align: center;}#sk-container-id-2 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-2 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-2\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>GridSearchCV(cv=5, estimator=DecisionTreeClassifier(),\n",
       "             param_grid={&#x27;criterion&#x27;: [&#x27;gini&#x27;, &#x27;entropy&#x27;],\n",
       "                         &#x27;max_depth&#x27;: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]},\n",
       "             scoring=&#x27;accuracy&#x27;)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-2\" type=\"checkbox\" ><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">GridSearchCV</label><div class=\"sk-toggleable__content\"><pre>GridSearchCV(cv=5, estimator=DecisionTreeClassifier(),\n",
       "             param_grid={&#x27;criterion&#x27;: [&#x27;gini&#x27;, &#x27;entropy&#x27;],\n",
       "                         &#x27;max_depth&#x27;: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]},\n",
       "             scoring=&#x27;accuracy&#x27;)</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-3\" type=\"checkbox\" ><label for=\"sk-estimator-id-3\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: DecisionTreeClassifier</label><div class=\"sk-toggleable__content\"><pre>DecisionTreeClassifier()</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-4\" type=\"checkbox\" ><label for=\"sk-estimator-id-4\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">DecisionTreeClassifier</label><div class=\"sk-toggleable__content\"><pre>DecisionTreeClassifier()</pre></div></div></div></div></div></div></div></div></div></div>"
      ],
      "text/plain": [
       "GridSearchCV(cv=5, estimator=DecisionTreeClassifier(),\n",
       "             param_grid={'criterion': ['gini', 'entropy'],\n",
       "                         'max_depth': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]},\n",
       "             scoring='accuracy')"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "DecisionTreeClassifier(max_depth=7)\n",
      "0.7200000000000001\n",
      "{'criterion': 'gini', 'max_depth': 7}\n"
     ]
    }
   ],
   "source": [
    "# grid search调参\n",
    "from sklearn.model_selection import GridSearchCV\n",
    "\n",
    "parameters = {\n",
    "    'criterion':['gini','entropy'],\n",
    "    'max_depth':[1,2,3,4,5,6,7,8,9,10,11,12]\n",
    "}\n",
    "\n",
    "dtree = tree.DecisionTreeClassifier()\n",
    "dtree_search = GridSearchCV(dtree, parameters, scoring='accuracy', cv=5)\n",
    "dtree_search.fit(X_train, y_train)\n",
    "\n",
    "#查看最佳结果\n",
    "print(dtree_search.best_estimator_)\n",
    "print(dtree_search.best_score_)\n",
    "print(dtree_search.best_params_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "e7a843c6-b5ff-4523-9a02-07892ca91ed2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-3 {color: black;background-color: white;}#sk-container-id-3 pre{padding: 0;}#sk-container-id-3 div.sk-toggleable {background-color: white;}#sk-container-id-3 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-3 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-3 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-3 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-3 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-3 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-3 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-3 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-3 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-3 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-3 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-3 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-3 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-3 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-3 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-3 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-3 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-3 div.sk-item {position: relative;z-index: 1;}#sk-container-id-3 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-3 div.sk-item::before, #sk-container-id-3 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-3 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-3 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-3 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-3 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-3 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-3 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-3 div.sk-label-container {text-align: center;}#sk-container-id-3 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-3 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-3\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>DecisionTreeClassifier(max_depth=7)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-5\" type=\"checkbox\" checked><label for=\"sk-estimator-id-5\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">DecisionTreeClassifier</label><div class=\"sk-toggleable__content\"><pre>DecisionTreeClassifier(max_depth=7)</pre></div></div></div></div></div>"
      ],
      "text/plain": [
       "DecisionTreeClassifier(max_depth=7)"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 用最佳参数重新训练模型\n",
    "dtree = DecisionTreeClassifier(criterion='gini',max_depth=7)\n",
    "dtree.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9c102574-e2a4-47eb-8ec7-4311418feab2",
   "metadata": {},
   "source": [
    "# 课堂训练：鸢尾花"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "a4230507-3c26-43e9-9501-e7e5fb02ea5d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>1</th>\n",
       "      <th>2</th>\n",
       "      <th>3</th>\n",
       "      <th>4</th>\n",
       "      <th>lris</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>5.1</td>\n",
       "      <td>3.5</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "      <td>Iris-setosa</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4.9</td>\n",
       "      <td>3.0</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "      <td>Iris-setosa</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4.7</td>\n",
       "      <td>3.2</td>\n",
       "      <td>1.3</td>\n",
       "      <td>0.2</td>\n",
       "      <td>Iris-setosa</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4.6</td>\n",
       "      <td>3.1</td>\n",
       "      <td>1.5</td>\n",
       "      <td>0.2</td>\n",
       "      <td>Iris-setosa</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5.0</td>\n",
       "      <td>3.6</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "      <td>Iris-setosa</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     1    2    3    4         lris\n",
       "0  5.1  3.5  1.4  0.2  Iris-setosa\n",
       "1  4.9  3.0  1.4  0.2  Iris-setosa\n",
       "2  4.7  3.2  1.3  0.2  Iris-setosa\n",
       "3  4.6  3.1  1.5  0.2  Iris-setosa\n",
       "4  5.0  3.6  1.4  0.2  Iris-setosa"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 利用pandas导入csv数据，查看前5行导入结果看是否正常\n",
    "import pandas as pd\n",
    "credit_df = pd.read_csv(\"irisdata.txt\", header=None)\n",
    "#源DataFrame中是没有索引的，此处加上索引\n",
    "new_column_names =['1','2','3','4','lris']\n",
    "credit_df.columns = new_column_names\n",
    "credit_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "638078f5-59fb-4286-bfd8-e1064787137a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 150 entries, 0 to 149\n",
      "Data columns (total 5 columns):\n",
      " #   Column  Non-Null Count  Dtype  \n",
      "---  ------  --------------  -----  \n",
      " 0   1       150 non-null    float64\n",
      " 1   2       150 non-null    float64\n",
      " 2   3       150 non-null    float64\n",
      " 3   4       150 non-null    float64\n",
      " 4   lris    150 non-null    object \n",
      "dtypes: float64(4), object(1)\n",
      "memory usage: 6.0+ KB\n"
     ]
    }
   ],
   "source": [
    "credit_df.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "e5017906-8801-458f-8cfa-3080efcc78a7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1       0\n",
       "2       0\n",
       "3       0\n",
       "4       0\n",
       "lris    0\n",
       "dtype: int64"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "credit_df.isnull().sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "id": "4743f2bb-c0ab-440a-af9d-175adfb76f8f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>1</th>\n",
       "      <th>2</th>\n",
       "      <th>3</th>\n",
       "      <th>4</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>150.000000</td>\n",
       "      <td>150.000000</td>\n",
       "      <td>150.000000</td>\n",
       "      <td>150.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>5.843333</td>\n",
       "      <td>3.054000</td>\n",
       "      <td>3.758667</td>\n",
       "      <td>1.198667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>0.828066</td>\n",
       "      <td>0.433594</td>\n",
       "      <td>1.764420</td>\n",
       "      <td>0.763161</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>4.300000</td>\n",
       "      <td>2.000000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>0.100000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>5.100000</td>\n",
       "      <td>2.800000</td>\n",
       "      <td>1.600000</td>\n",
       "      <td>0.300000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>5.800000</td>\n",
       "      <td>3.000000</td>\n",
       "      <td>4.350000</td>\n",
       "      <td>1.300000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>6.400000</td>\n",
       "      <td>3.300000</td>\n",
       "      <td>5.100000</td>\n",
       "      <td>1.800000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>7.900000</td>\n",
       "      <td>4.400000</td>\n",
       "      <td>6.900000</td>\n",
       "      <td>2.500000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                1           2           3           4\n",
       "count  150.000000  150.000000  150.000000  150.000000\n",
       "mean     5.843333    3.054000    3.758667    1.198667\n",
       "std      0.828066    0.433594    1.764420    0.763161\n",
       "min      4.300000    2.000000    1.000000    0.100000\n",
       "25%      5.100000    2.800000    1.600000    0.300000\n",
       "50%      5.800000    3.000000    4.350000    1.300000\n",
       "75%      6.400000    3.300000    5.100000    1.800000\n",
       "max      7.900000    4.400000    6.900000    2.500000"
      ]
     },
     "execution_count": 68,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "credit_df.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "33587eb3-3e4c-42ff-846f-3a7fe6e3fa62",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>1</th>\n",
       "      <th>2</th>\n",
       "      <th>3</th>\n",
       "      <th>4</th>\n",
       "      <th>lris</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>34</th>\n",
       "      <td>4.9</td>\n",
       "      <td>3.1</td>\n",
       "      <td>1.5</td>\n",
       "      <td>0.1</td>\n",
       "      <td>Iris-setosa</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>37</th>\n",
       "      <td>4.9</td>\n",
       "      <td>3.1</td>\n",
       "      <td>1.5</td>\n",
       "      <td>0.1</td>\n",
       "      <td>Iris-setosa</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>142</th>\n",
       "      <td>5.8</td>\n",
       "      <td>2.7</td>\n",
       "      <td>5.1</td>\n",
       "      <td>1.9</td>\n",
       "      <td>Iris-virginica</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       1    2    3    4            lris\n",
       "34   4.9  3.1  1.5  0.1     Iris-setosa\n",
       "37   4.9  3.1  1.5  0.1     Iris-setosa\n",
       "142  5.8  2.7  5.1  1.9  Iris-virginica"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "credit_df[credit_df.duplicated()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "id": "926d554c-9c24-40e9-a3d7-51e4554b3a52",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>1</th>\n",
       "      <th>2</th>\n",
       "      <th>3</th>\n",
       "      <th>4</th>\n",
       "      <th>lris</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>5.1</td>\n",
       "      <td>3.5</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "      <td>Iris-setosa</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>4.9</td>\n",
       "      <td>3.0</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "      <td>Iris-setosa</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4.7</td>\n",
       "      <td>3.2</td>\n",
       "      <td>1.3</td>\n",
       "      <td>0.2</td>\n",
       "      <td>Iris-setosa</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4.6</td>\n",
       "      <td>3.1</td>\n",
       "      <td>1.5</td>\n",
       "      <td>0.2</td>\n",
       "      <td>Iris-setosa</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5.0</td>\n",
       "      <td>3.6</td>\n",
       "      <td>1.4</td>\n",
       "      <td>0.2</td>\n",
       "      <td>Iris-setosa</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     1    2    3    4         lris\n",
       "0  5.1  3.5  1.4  0.2  Iris-setosa\n",
       "1  4.9  3.0  1.4  0.2  Iris-setosa\n",
       "2  4.7  3.2  1.3  0.2  Iris-setosa\n",
       "3  4.6  3.1  1.5  0.2  Iris-setosa\n",
       "4  5.0  3.6  1.4  0.2  Iris-setosa"
      ]
     },
     "execution_count": 70,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "credit_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "b1076a34-897b-4870-915d-da5ab378ceb0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1    50\n",
       "2    50\n",
       "3    50\n",
       "Name: target, dtype: int64"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 构造目标变量y的数据对象\n",
    "credit_df['target'] = 0\n",
    "credit_df.loc[(credit_df.lris == 'Iris-setosa'), 'target'] = 1\n",
    "credit_df.loc[(credit_df.lris == 'Iris-versicolor'), 'target'] = 2\n",
    "credit_df.loc[(credit_df.lris == 'Iris-virginica'), 'target'] = 3\n",
    "\n",
    "\n",
    "trainData_y = credit_df['target'] \n",
    "# 数值统计\n",
    "trainData_y.value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "id": "438c0a33-fb9e-4bd4-b7e5-47093efa938c",
   "metadata": {},
   "outputs": [],
   "source": [
    "trainData_X = credit_df.drop(columns=['lris','target'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "697eb435-4694-44a9-8bd1-083d2ce2aa7d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       1    2    3    4\n",
      "0    5.1  3.5  1.4  0.2\n",
      "1    4.9  3.0  1.4  0.2\n",
      "2    4.7  3.2  1.3  0.2\n",
      "3    4.6  3.1  1.5  0.2\n",
      "4    5.0  3.6  1.4  0.2\n",
      "..   ...  ...  ...  ...\n",
      "145  6.7  3.0  5.2  2.3\n",
      "146  6.3  2.5  5.0  1.9\n",
      "147  6.5  3.0  5.2  2.0\n",
      "148  6.2  3.4  5.4  2.3\n",
      "149  5.9  3.0  5.1  1.8\n",
      "\n",
      "[150 rows x 4 columns]\n"
     ]
    }
   ],
   "source": [
    "print(trainData_X)\n",
    "#print(trainData_y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "id": "621c9243-de47-4647-97df-c9ae2229b8f2",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train,X_test,y_train,y_test  =  train_test_split(trainData_X, trainData_y,test_size=0.3, random_state=1024)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "id": "57a575b4-bbed-4a6c-8611-5cef466ce46f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(45,)"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_test.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "ac9157a9-0fe1-4974-9a91-68a9ef844230",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-7 {color: black;background-color: white;}#sk-container-id-7 pre{padding: 0;}#sk-container-id-7 div.sk-toggleable {background-color: white;}#sk-container-id-7 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-7 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-7 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-7 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-7 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-7 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-7 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-7 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-7 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-7 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-7 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-7 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-7 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-7 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-7 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-7 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-7 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-7 div.sk-item {position: relative;z-index: 1;}#sk-container-id-7 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-7 div.sk-item::before, #sk-container-id-7 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-7 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-7 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-7 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-7 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-7 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-7 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-7 div.sk-label-container {text-align: center;}#sk-container-id-7 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-7 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-7\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>DecisionTreeClassifier(max_depth=10)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-9\" type=\"checkbox\" checked><label for=\"sk-estimator-id-9\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">DecisionTreeClassifier</label><div class=\"sk-toggleable__content\"><pre>DecisionTreeClassifier(max_depth=10)</pre></div></div></div></div></div>"
      ],
      "text/plain": [
       "DecisionTreeClassifier(max_depth=10)"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.tree import DecisionTreeClassifier\n",
    "\n",
    "dtree = DecisionTreeClassifier(max_depth=10)\n",
    "dtree.fit(X_train,y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "id": "bcd52a8a-7585-4f62-ae7e-b709475d759b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.        , 0.04048721, 0.39524212, 0.56427067])"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dtree.feature_importances_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "id": "75324780-e687-4367-aac8-9bb3fd3fd55f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>feature</th>\n",
       "      <th>importance</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4</td>\n",
       "      <td>0.564271</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>0.395242</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>0.040487</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  feature  importance\n",
       "3       4    0.564271\n",
       "2       3    0.395242\n",
       "1       2    0.040487\n",
       "0       1    0.000000"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查看特征的重要性排序\n",
    "\n",
    "import pandas as pd\n",
    "features = pd.DataFrame()\n",
    "\n",
    "# 为空集合features创建两个列并赋值\n",
    "features['feature'] = X_train.columns\n",
    "features['importance'] = dtree.feature_importances_\n",
    "\n",
    "# 降序排列\n",
    "features = features.sort_values(by =['importance'], ascending=False)    \n",
    "\n",
    "# 显示最重要的前10个特征变量\n",
    "features.head(20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "id": "cd0fbd67-674d-4308-8fb7-91059b77c7a3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "45"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "id": "036174e4-9919-444c-827e-a8312c027569",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "              precision    recall  f1-score   support\n",
      "\n",
      "           1       1.00      1.00      1.00        14\n",
      "           2       1.00      0.94      0.97        16\n",
      "           3       0.94      1.00      0.97        15\n",
      "\n",
      "    accuracy                           0.98        45\n",
      "   macro avg       0.98      0.98      0.98        45\n",
      "weighted avg       0.98      0.98      0.98        45\n",
      "\n",
      "[[14  0  0]\n",
      " [ 0 15  1]\n",
      " [ 0  0 15]]\n"
     ]
    }
   ],
   "source": [
    "from sklearn.metrics import classification_report\n",
    "from sklearn.metrics import confusion_matrix\n",
    "\n",
    "# 利用模型对测试集进行预测，输出target预测标签值和概率\n",
    "y_test_pred = dtree.predict(X_test)\n",
    "y_test_prob = dtree.predict_proba(X_test)\n",
    "\n",
    "# 分类评估汇总报告classification_report\n",
    "print(classification_report(y_test,y_test_pred))\n",
    "\n",
    "# 误分类矩阵 confusion_matrix\n",
    "print(confusion_matrix(y_test,y_test_pred))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "id": "27bab89e-996b-44e0-8979-60f36434d159",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "45"
      ]
     },
     "execution_count": 90,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(y_test_pred)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45560b9e-0cdf-403f-96cd-3c42cdff3db4",
   "metadata": {},
   "source": [
    "# 随机森林"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "790493b5-234d-497e-acbc-b29fb29f5f19",
   "metadata": {},
   "source": [
    "### 训练随机森林模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "id": "0e9ba6b1-7312-47d5-9093-63f9933b4b5b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-8 {color: black;background-color: white;}#sk-container-id-8 pre{padding: 0;}#sk-container-id-8 div.sk-toggleable {background-color: white;}#sk-container-id-8 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-8 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-8 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-8 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-8 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-8 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-8 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-8 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-8 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-8 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-8 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-8 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-8 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-8 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-8 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-8 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-8 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-8 div.sk-item {position: relative;z-index: 1;}#sk-container-id-8 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-8 div.sk-item::before, #sk-container-id-8 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-8 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-8 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-8 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-8 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-8 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-8 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-8 div.sk-label-container {text-align: center;}#sk-container-id-8 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-8 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-8\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>RandomForestClassifier()</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-10\" type=\"checkbox\" checked><label for=\"sk-estimator-id-10\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">RandomForestClassifier</label><div class=\"sk-toggleable__content\"><pre>RandomForestClassifier()</pre></div></div></div></div></div>"
      ],
      "text/plain": [
       "RandomForestClassifier()"
      ]
     },
     "execution_count": 91,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "# 通过RandomForestClassifier类定义一个随机森林模型，名字叫rf\n",
    "rf = RandomForestClassifier(n_estimators = 100)\n",
    "\n",
    "# 对lr模型进行训练(fit)\n",
    "rf.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "id": "ce47dc93-ba57-423d-aecb-f9dceb0e3f66",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "              precision    recall  f1-score   support\n",
      "\n",
      "           1       1.00      1.00      1.00        14\n",
      "           2       1.00      0.94      0.97        16\n",
      "           3       0.94      1.00      0.97        15\n",
      "\n",
      "    accuracy                           0.98        45\n",
      "   macro avg       0.98      0.98      0.98        45\n",
      "weighted avg       0.98      0.98      0.98        45\n",
      "\n",
      "[[14  0  0]\n",
      " [ 0 15  1]\n",
      " [ 0  0 15]]\n"
     ]
    }
   ],
   "source": [
    "from sklearn.metrics import classification_report\n",
    "from sklearn.metrics import confusion_matrix\n",
    "from sklearn.metrics import roc_curve\n",
    "from sklearn.metrics import auc\n",
    "\n",
    "# 利用模型对测试集进行预测，输出target预测标签值和概率\n",
    "y_test_pred = rf.predict(X_test)\n",
    "y_test_prob = rf.predict_proba(X_test)\n",
    "\n",
    "# 分类评估汇总报告classification_report\n",
    "print(classification_report(y_test,y_test_pred))\n",
    "\n",
    "# 误分类矩阵 confusion_matrix\n",
    "print(confusion_matrix(y_test,y_test_pred))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca6eab38-c127-4369-9f14-af64b273191c",
   "metadata": {},
   "source": [
    "# 作业：用随机森林处理数据（18min）\n",
    "最后一列是标签，归一化，重要性排列和最后数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "fe857d79-498e-4b9e-b04c-a5045b8c51ab",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>column_1</th>\n",
       "      <th>column_2</th>\n",
       "      <th>column_3</th>\n",
       "      <th>column_4</th>\n",
       "      <th>column_5</th>\n",
       "      <th>column_6</th>\n",
       "      <th>column_7</th>\n",
       "      <th>column_8</th>\n",
       "      <th>column_9</th>\n",
       "      <th>column_10</th>\n",
       "      <th>column_11</th>\n",
       "      <th>column_12</th>\n",
       "      <th>column_13</th>\n",
       "      <th>column_14</th>\n",
       "      <th>column_15</th>\n",
       "      <th>column_16</th>\n",
       "      <th>name</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>47</td>\n",
       "      <td>100</td>\n",
       "      <td>27</td>\n",
       "      <td>81</td>\n",
       "      <td>57</td>\n",
       "      <td>37</td>\n",
       "      <td>26</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>23</td>\n",
       "      <td>56</td>\n",
       "      <td>53</td>\n",
       "      <td>100</td>\n",
       "      <td>90</td>\n",
       "      <td>40</td>\n",
       "      <td>98</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0</td>\n",
       "      <td>89</td>\n",
       "      <td>27</td>\n",
       "      <td>100</td>\n",
       "      <td>42</td>\n",
       "      <td>75</td>\n",
       "      <td>29</td>\n",
       "      <td>45</td>\n",
       "      <td>15</td>\n",
       "      <td>15</td>\n",
       "      <td>37</td>\n",
       "      <td>0</td>\n",
       "      <td>69</td>\n",
       "      <td>2</td>\n",
       "      <td>100</td>\n",
       "      <td>6</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0</td>\n",
       "      <td>57</td>\n",
       "      <td>31</td>\n",
       "      <td>68</td>\n",
       "      <td>72</td>\n",
       "      <td>90</td>\n",
       "      <td>100</td>\n",
       "      <td>100</td>\n",
       "      <td>76</td>\n",
       "      <td>75</td>\n",
       "      <td>50</td>\n",
       "      <td>51</td>\n",
       "      <td>28</td>\n",
       "      <td>25</td>\n",
       "      <td>16</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0</td>\n",
       "      <td>100</td>\n",
       "      <td>7</td>\n",
       "      <td>92</td>\n",
       "      <td>5</td>\n",
       "      <td>68</td>\n",
       "      <td>19</td>\n",
       "      <td>45</td>\n",
       "      <td>86</td>\n",
       "      <td>34</td>\n",
       "      <td>100</td>\n",
       "      <td>45</td>\n",
       "      <td>74</td>\n",
       "      <td>23</td>\n",
       "      <td>67</td>\n",
       "      <td>0</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0</td>\n",
       "      <td>67</td>\n",
       "      <td>49</td>\n",
       "      <td>83</td>\n",
       "      <td>100</td>\n",
       "      <td>100</td>\n",
       "      <td>81</td>\n",
       "      <td>80</td>\n",
       "      <td>60</td>\n",
       "      <td>60</td>\n",
       "      <td>40</td>\n",
       "      <td>40</td>\n",
       "      <td>33</td>\n",
       "      <td>20</td>\n",
       "      <td>47</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   column_1  column_2  column_3  column_4  column_5  column_6  column_7  \\\n",
       "0        47       100        27        81        57        37        26   \n",
       "1         0        89        27       100        42        75        29   \n",
       "2         0        57        31        68        72        90       100   \n",
       "3         0       100         7        92         5        68        19   \n",
       "4         0        67        49        83       100       100        81   \n",
       "\n",
       "   column_8  column_9  column_10  column_11  column_12  column_13  column_14  \\\n",
       "0         0         0         23         56         53        100         90   \n",
       "1        45        15         15         37          0         69          2   \n",
       "2       100        76         75         50         51         28         25   \n",
       "3        45        86         34        100         45         74         23   \n",
       "4        80        60         60         40         40         33         20   \n",
       "\n",
       "   column_15  column_16  name  \n",
       "0         40         98     8  \n",
       "1        100          6     2  \n",
       "2         16          0     1  \n",
       "3         67          0     4  \n",
       "4         47          0     1  "
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 利用pandas导入csv数据，查看前5行导入结果看是否正常\n",
    "import pandas as pd\n",
    "credit_df = pd.read_csv(\"pendigits.txt\", header=None)\n",
    "#源DataFrame中是没有索引的，此处加上索引\n",
    "new_column_names =[f'column_{i}' for i in range(1,17)]+['name']\n",
    "credit_df.columns = new_column_names\n",
    "credit_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "0bdc4461-fd8e-4bf8-83a4-24b51fc5e683",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 7494 entries, 0 to 7493\n",
      "Data columns (total 17 columns):\n",
      " #   Column     Non-Null Count  Dtype\n",
      "---  ------     --------------  -----\n",
      " 0   column_1   7494 non-null   int64\n",
      " 1   column_2   7494 non-null   int64\n",
      " 2   column_3   7494 non-null   int64\n",
      " 3   column_4   7494 non-null   int64\n",
      " 4   column_5   7494 non-null   int64\n",
      " 5   column_6   7494 non-null   int64\n",
      " 6   column_7   7494 non-null   int64\n",
      " 7   column_8   7494 non-null   int64\n",
      " 8   column_9   7494 non-null   int64\n",
      " 9   column_10  7494 non-null   int64\n",
      " 10  column_11  7494 non-null   int64\n",
      " 11  column_12  7494 non-null   int64\n",
      " 12  column_13  7494 non-null   int64\n",
      " 13  column_14  7494 non-null   int64\n",
      " 14  column_15  7494 non-null   int64\n",
      " 15  column_16  7494 non-null   int64\n",
      " 16  name       7494 non-null   int64\n",
      "dtypes: int64(17)\n",
      "memory usage: 995.4 KB\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>column_1</th>\n",
       "      <th>column_2</th>\n",
       "      <th>column_3</th>\n",
       "      <th>column_4</th>\n",
       "      <th>column_5</th>\n",
       "      <th>column_6</th>\n",
       "      <th>column_7</th>\n",
       "      <th>column_8</th>\n",
       "      <th>column_9</th>\n",
       "      <th>column_10</th>\n",
       "      <th>column_11</th>\n",
       "      <th>column_12</th>\n",
       "      <th>column_13</th>\n",
       "      <th>column_14</th>\n",
       "      <th>column_15</th>\n",
       "      <th>column_16</th>\n",
       "      <th>name</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "Empty DataFrame\n",
       "Columns: [column_1, column_2, column_3, column_4, column_5, column_6, column_7, column_8, column_9, column_10, column_11, column_12, column_13, column_14, column_15, column_16, name]\n",
       "Index: []"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "credit_df.info()\n",
    "credit_df.describe()\n",
    "credit_df.isnull().sum()\n",
    "credit_df[credit_df.duplicated()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "268e23f4-78b5-4f2e-b7c9-e3fa638bbb7f",
   "metadata": {},
   "outputs": [],
   "source": [
    "target=[]\n",
    "target =credit_df.name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "23592e5f-12b6-4bfd-b710-75e2d258c276",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(7494,)"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "target.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "d0247437-dec1-4f57-8421-ddf716ab1ff0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(7494, 16)\n"
     ]
    }
   ],
   "source": [
    "trainData_X_1 = credit_df.drop(columns=['name'])\n",
    "\n",
    "from sklearn import preprocessing\n",
    "import numpy as np\n",
    "\n",
    "trainData_X = preprocessing.normalize(trainData_X_1, norm='l2')\n",
    "print(trainData_X.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "5d6b184d-d48d-43bf-a16a-7f599cd11829",
   "metadata": {},
   "outputs": [],
   "source": [
    "trainData_y=target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "8c8909f1-e0bb-4ab2-a9fb-c07341c922a7",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train,X_test,y_train,y_test  =  train_test_split(trainData_X, trainData_y,test_size=0.3, random_state=1024)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "3558ddbf-f471-41aa-88b2-964274ecc0b3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-1 {color: black;background-color: white;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>RandomForestClassifier()</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" checked><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">RandomForestClassifier</label><div class=\"sk-toggleable__content\"><pre>RandomForestClassifier()</pre></div></div></div></div></div>"
      ],
      "text/plain": [
       "RandomForestClassifier()"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "# 通过RandomForestClassifier类定义一个随机森林模型，名字叫rf\n",
    "rf = RandomForestClassifier(n_estimators = 100)\n",
    "\n",
    "# 对lr模型进行训练(fit)\n",
    "rf.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "5579ac37-8c9d-42bc-a551-e9d33d8cde09",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.99      0.99      0.99       245\n",
      "           1       0.96      0.97      0.97       244\n",
      "           2       0.98      0.98      0.98       244\n",
      "           3       0.99      0.99      0.99       191\n",
      "           4       1.00      0.98      0.99       232\n",
      "           5       1.00      0.99      0.99       212\n",
      "           6       1.00      1.00      1.00       216\n",
      "           7       0.99      0.99      0.99       228\n",
      "           8       0.99      0.99      0.99       226\n",
      "           9       0.98      1.00      0.99       211\n",
      "\n",
      "    accuracy                           0.99      2249\n",
      "   macro avg       0.99      0.99      0.99      2249\n",
      "weighted avg       0.99      0.99      0.99      2249\n",
      "\n",
      "[[243   0   0   0   0   0   0   0   2   0]\n",
      " [  0 237   4   1   0   0   0   0   0   2]\n",
      " [  0   4 239   0   0   0   0   1   0   0]\n",
      " [  0   0   0 189   0   0   0   2   0   0]\n",
      " [  0   2   0   0 228   0   0   0   0   2]\n",
      " [  0   0   0   1   0 210   0   0   0   1]\n",
      " [  0   0   0   0   0   1 215   0   0   0]\n",
      " [  0   3   0   0   0   0   0 225   0   0]\n",
      " [  2   0   0   0   0   0   0   0 224   0]\n",
      " [  0   0   0   0   0   0   0   0   0 211]]\n"
     ]
    }
   ],
   "source": [
    "from sklearn.metrics import classification_report\n",
    "from sklearn.metrics import confusion_matrix\n",
    "from sklearn.metrics import roc_curve\n",
    "from sklearn.metrics import auc\n",
    "\n",
    "# 利用模型对测试集进行预测，输出target预测标签值和概率\n",
    "y_test_pred = rf.predict(X_test)\n",
    "y_test_prob = rf.predict_proba(X_test)\n",
    "\n",
    "# 分类评估汇总报告classification_report\n",
    "print(classification_report(y_test,y_test_pred))\n",
    "\n",
    "# 误分类矩阵 confusion_matrix\n",
    "print(confusion_matrix(y_test,y_test_pred))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dcec0ab7-6497-49ca-b833-229e5335e009",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
